package com.html2rss.ui.wizard;

import com.html2rss.core.parser.HTMLFeedExtracter;
import com.html2rss.core.DomHelper;
import com.html2rss.models.Query;
import com.html2rss.models.WizardHistory;
import com.html2rss.models.WizardHistoryPage;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.xpath.XPathExpressionException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * User: vvs
 * Date: 12.04.2007
 * Time: 23:36:55
 */
public class SelectFeedAction extends BaseWizardAction {

    public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        WizardHistory wnh = getWizardNavigationHistory(httpServletRequest);
        int lastPageNumber = wnh.size() - 1;
        WizardHistoryPage lastPage = wnh.get(lastPageNumber);
        Document lastPageDoc = wnh.getDoc(lastPageNumber);

        Query qnode = new Query(findNodes(lastPageDoc, httpServletRequest.getParameter(FEED_TAG_IDS).split("_")));
        wnh.setFeedSuggestions(generateFeedQueries(qnode, lastPageDoc));

        ArrayList feeds = new ArrayList();
        for (int i = 0; i < wnh.getFeedSuggestions().size(); i++) {
            String feed = "";
            Query qfeed = wnh.getFeedSuggestions().get(i);
            feed += ("<b>Feed #" + i +" (" +qfeed.getPath()+")</b> <br>");
            List<Node> nodes = qfeed.execute(lastPageDoc);
            for (Node node : nodes) {
                feed += HTMLFeedExtracter.saveXMLDocumentToString(node);
                feed+="<br>****<br>";
            }
            feeds.add(feed + "<hr>");
        }
        httpServletRequest.setAttribute("feeds", feeds);


        return actionMapping.findForward("success");
    }

    private List<Query> generateFeedQueries(Query qnode, Document doc) throws XPathExpressionException {
        List <Query> result = new ArrayList<Query>();
        Set<List<Node>> set = new HashSet<List<Node>>();
        for (int i = qnode.getPathToRoot().size() - 1; i >= 0; i--) {
            Query temp = (Query) qnode.clone();
            temp.getPathToRootInd().set(i, -1);
            List<Node> feed = temp.execute(doc);
            if (!set.contains(feed)) {
                result.add(temp);
                set.add(feed);
            }
        }
        Query temp = (Query) qnode.clone();
        String last = temp.getPathToRoot().get(temp.getPathToRoot().size()-1);
        ArrayList<String> list = new ArrayList<String>();
        list.add("/");
        list.add(last);
        temp.setPathToRoot(list);
        List<Node> feed = temp.execute(doc);
        if (!set.contains(feed)) {
            result.add(temp);
            set.add(feed);
        }
        return result;
    }

    private List<Node> findNodes(Document doc, String[] strings) {
        ArrayList<Node> result = new ArrayList<Node>();
        for (String s : strings) {
            result.addAll(DomHelper.findNodesByAttrValue(doc, NavigateToHTMLPageAction.HTML_TO_RSS_ID, s));
        }
        return result;
    }


}
